package ren.nearby.home;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.Settings;
import android.support.annotation.RequiresApi;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.FileProvider;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.ogaclejapan.smarttablayout.SmartTabLayout;
import com.ogaclejapan.smarttablayout.utils.v4.FragmentPagerItemAdapter;
import com.ogaclejapan.smarttablayout.utils.v4.FragmentPagerItems;
import com.orhanobut.logger.Logger;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import hugo.weaving.DebugLog;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import ren.nearby.bean.beans.LoginBean;
import ren.nearby.bean.beans.VersionBean;
import ren.nearby.home.mvp.FragmentActAction;
import ren.nearby.home.mvp.FragmentContract;
import ren.nearby.lib.http.permission.Permission;
import ren.nearby.lib.http.permission.RxPermissions;
import ren.nearby.lib.ui.base.BaseActivity;
import ren.nearby.lib.ui.permission.PermissionBean;
import ren.nearby.lib.ui.permission.PermissionBuild;


public class ANearbyMain extends BaseActivity implements
        ViewPager.OnPageChangeListener,
        FragmentContract.View,
        VersionCodeDialogFragment.OnCancelClick {


    //    @BindView(R2.id.home_tabLayout)
    public SmartTabLayout home_tabLayout;
    //    @BindView(R2.id.home_viewPager)
    public NearbyViewPager home_viewPager;

    @Override
    public int getLayoutRes() {
        return R.layout.home_activity_anearby_main;
    }

    @Override
    public void setPresenter(FragmentActAction presenter) {

    }

    @Override
    public void onIntent() {
        action.takeView(this);
        rxPermissions = new RxPermissions(getActivity());
        isPermission();
    }
    RxPermissions rxPermissions;
    ArrayList<PermissionBean> request = new ArrayList<>();
    public void isPermission() {
        List<PermissionBean> permissions = new ArrayList<>();
        permissions.add(new PermissionBean(Manifest.permission.ACCESS_FINE_LOCATION, R.mipmap.easy_location, "开启定位功能", "GPS定位开启，便于筛选城市车辆"));
        permissions.add(new PermissionBean(android.Manifest.permission.
                WRITE_EXTERNAL_STORAGE, R.mipmap.easy_storage, "存储权限", "缓存图片，降低流量消耗"));
        permissions.add(new PermissionBean(android.Manifest.permission.
                CAMERA, R.mipmap.easy_camera, "相机权限", "资料提交需要开启相机"));
        for (PermissionBean permission : permissions) {
            if (!rxPermissions.isGranted(permission.getName()) && !rxPermissions.isRevoked(permission.getName())) {
                request.add(permission);
            }
        }
        final PermissionBuild.Builder builder = new PermissionBuild.Builder((BaseActivity) getActivity());
        builder.
                setRequest(request)
                .setPermiCancel(new PermissionBuild.PermiCancel() {
                    @Override
                    public void perCancel() {
                        Logger.e("Cancel");
                    }
                }).setPermiOk(new PermissionBuild.PermiOk() {
            @Override
            public void perOk() {
                Logger.e("Ok");
                singlePermissions();
            }
        }).build();

    }
    public void singlePermissions() {
        rxPermissions.ensureEach(
                Manifest.permission.CALL_PHONE,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.CAMERA,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE)
                .apply(new Observable<Object>() {
                    @Override
                    protected void subscribeActual(final Observer<? super Object> observer) {
                        Logger.e("subscribeActual = ");
                        observer.onNext(observer);
                        observer.onComplete();
               /* dialog = new PublicDialog.Builder(getActivity())
                        .setbody("我是内容帅气的小脸蛋")
                        .setTextTitle("我是标题栏")
                        .setPositiveButtonText("确认")
                        .setPositiveTextColor(R.color.red)
                        .setOnPositiveClicked(new PublicDialog.OnPositiveClicked() {
                            @Override
                            public void OnClick(View view, Dialog dialog) {
                                Logger.e("确认");
                                observer.onNext(observer);
                            }
                        })
                        .setNegativeButtonText("取消")
                        .setNegativeTextColor(R.color.white)
                        .setOnNegativeClicked(new PublicDialog.OnNegativeClicked() {
                            @Override
                            public void OnClick(View view, Dialog dialog) {
                                Logger.e("取消");

                            }
                        }).setCancelable(false)
                        .build();
                dialog.show();*/


                    }
                }).subscribe(new Observer<Permission>() {
            @Override
            public void onSubscribe(Disposable d) {
                Logger.e("onSubscribe = " + d.isDisposed());
            }

            @Override
            public void onNext(Permission permission) {
                Logger.e("onNext = " + permission.granted);

                if (permission.granted) {
                    Logger.e("已经授权的权限" + permission.name);
                } else if (permission.shouldShowRequestPermissionRationale) {
                    //拒绝
                    Logger.e("已经拒绝的权限" + permission.name);
                } else {
                    //拒绝 不再询问
                    Logger.e("不再询问的权限" + permission.name);
                }

            }

            @Override
            public void onError(Throwable e) {
                Logger.e("onError = " + e.toString());
            }

            @Override
            public void onComplete() {
                Logger.e("onComplete = ");

            }
        });
    }
    @Inject
    FragmentContract.Action action;

    @Inject
    LoginBean loginBean;

    @Override
    public void initView() {
        super.initView();
        home_tabLayout = findViewById(R.id.home_tabLayout);
        home_viewPager = findViewById(R.id.home_viewPager);
        FragmentPagerItems pages = FragmentPagerItems.with(this)
                .add(R.string.home_nearby_fragment_home, NearbyFragmentHome.class)
                .add(R.string.home_nearby_fragment_message, NearbyFragmentMessage.class)
                .add(R.string.home_nearby_fragment_me, NearbyFragmentMe.class)
                .create();
        FragmentPagerItemAdapter adapter = new FragmentPagerItemAdapter(
                getSupportFragmentManager(),
                pages);
        Logger.e(home_viewPager == null ? "1" : "0");
        home_viewPager.setOffscreenPageLimit(pages.size());
        home_viewPager.setAdapter(adapter);
        home_viewPager.setScanScroll(true);
        home_viewPager.addOnPageChangeListener(this);
        setup(home_tabLayout);
        home_tabLayout.setViewPager(home_viewPager);
        if (action != null) {
            action.test();
        } else {
            Logger.e("action null ");
        }

        Logger.e(loginBean == null ?
                "value = 1" :
                " value = 0" + loginBean.getUsername() + " - " + loginBean.isIps());
        //测试Carch库
//    testCrach();
        //版本更新
//        VersionBean bean = new VersionBean();
//        bean.setUpdateType(1);
//        bean.setUpdate(0);
//        bean.setUrl("https://imtt.dd.qq.com/16891/0901AF27C922B428A422CAFBC1B3C398.apk");
//        bean.setRemark("1.修复了一些BUG; \n2.优化了一部分功能BUG\n3.优化部分UI界面\n4.新增了选车模式方案信息");
//        showUpload(bean);

    }


    @Override
    public void showUpload(VersionBean bean) {
        if (bean.getUpdate() == 0) {
            showVersion(bean);
        }

    }

    VersionCodeDialogFragment dialogV;

    @Override
    public void cancelV() {
        if (dialogV != null) {
            dialogV.dismiss();
        }

    }

    @Override
    public void updateV(String url,
                        String fileStoreDir,
                        String fileStoreName
    ) {
        Logger.e("updateV " + url);
        action.updateApk(url,
                fileStoreDir,
                fileStoreName
        );
    }

    @Override
    public void installV() {
        Logger.e("installV");
        installation();
    }

    public void showVersion(VersionBean bean) {
        boolean install;
//        String fileStoreDir = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "yifengrent";
        String fileStoreDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "";
        String fileStoreName = "nearby_" + bean.getInversion() + ".apk";
        file = new File(fileStoreDir, fileStoreName);
        if (!file.exists()) {
            Logger.e("不存在...");
            install = false;
        } else {
            Logger.e("存在...");
            install = true;

        }
        dialogV =
                VersionCodeDialogFragment
                        .newInstance(
                                bean.getUpdateType(),
                                bean.getUrl(),
                                fileStoreDir,
                                fileStoreName,
                                bean.getRemark(),
                                install);
        FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
        transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
        dialogV.setOnCancelClick(this);
        dialogV.show(transaction, "dialog_v");
    }

    NotificationManager notificationManager;
    NotificationCompat.Builder builder;
    Notification notification;

    @TargetApi(Build.VERSION_CODES.O)
    private void createNotificationChannel(String channelId, String channelName, int importance) {
        NotificationChannel channel = new NotificationChannel(channelId, channelName, importance);
        notificationManager.createNotificationChannel(channel);
    }

    private static final String YOUR_CHANNEL_ID = "YOUR_NOTIFY_ID";
    private static final String YOUR_CHANNEL_NAME = "YOUR_NOTIFY_NAME";

    @Override
    public void startUi() {
        Logger.e("启动");
        notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            Logger.e("8.0以上");

            createNotificationChannel(YOUR_CHANNEL_ID, YOUR_CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
            builder = new NotificationCompat
                    .Builder(getApplicationContext(), YOUR_CHANNEL_ID)
//                    .setContentTitle("正在更新...")
                    .setChannelId(YOUR_CHANNEL_ID)
//                    .setContentText("下载进度:" + "0%")
//                    .setSmallIcon(R.drawable.icon_dotview)
                    .setWhen(System.currentTimeMillis())
                    .setAutoCancel(true);


        } else {
            Logger.e("8.0以下");
            builder = new NotificationCompat
                    .Builder(getApplicationContext())
//                    .setContentTitle("正在更新...")
                    .setChannelId(YOUR_CHANNEL_ID)
//                    .setContentText("下载进度:" + "0%")
//                    .setSmallIcon(R.drawable.icon_dotview)
                    .setWhen(System.currentTimeMillis())
                    .setAutoCancel(true);

        }

        notification = builder.build();
        notificationManager.notify(1, notification);
        ////延迟意图
        PendingIntent contentIntent = PendingIntent.getActivity(this, R.string.app_name, new Intent(),
                PendingIntent.FLAG_UPDATE_CURRENT);
        notification.contentIntent = contentIntent;
        notification.flags = Notification.FLAG_AUTO_CANCEL;


    }


    @Override
    public void setProgress(long contentLength, long progress, long total) {
        dialogV.setUProgress("下载进度：" + (int) ((100 * progress) / contentLength) + "%");
        Logger.e("进度" + (100 * progress) / contentLength);
//        builder.setProgress(100, (int) ((100 * progress) / contentLength), false);
//        builder.setContentText("下载进度：" + (int) ((100 * progress) / contentLength) + "%");
//        notification = builder.build();
//        notificationManager.notify(1, notification);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 10086) {
            Logger.e("来安装...");
            installation();
        }
    }

    File file;

    @Override
    public void installationApk(File file) {
        Logger.e("安装");
        this.file = file;
        dialogV.setInstall();

//        installation();
    }

    public void installation() {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        //兼容7.0
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Uri contentUri = FileProvider.getUriForFile(this, "www.nearby.ren.fileprovider", file);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Logger.e("安装进来 Build.VERSION_CODES.N");
            //兼容8.0
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                Logger.e("安装进来 Build.VERSION_CODES.O");
                boolean hasInstallPermission = getPackageManager().canRequestPackageInstalls();
                if (!hasInstallPermission) {
                    startInstallPermissionSettingActivity();
                    return;
                }
            }
        } else {
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        if (getPackageManager().queryIntentActivities(intent, 0).size() > 0) {
            if (notificationManager != null) {
                notificationManager.cancel(1);
            }

            startActivity(intent);

        }
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private void startInstallPermissionSettingActivity() {
        //注意这个是8.0新API
        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, Uri.parse("package:" + getPackageName()));
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivityForResult(intent, 10086);
    }


    public void testCrach() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                throw new NullPointerException("00");
            }
        }).start();
    }

    //    @DebugLog


    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @DebugLog
    //添加tab图标
    public void setup(SmartTabLayout layout) {
        layout.setCustomTabView(new SmartTabLayout.TabProvider() {
            @Override
            public View createTabView(ViewGroup container, int position, PagerAdapter adapter) {
                View view = LayoutInflater.from(ANearbyMain.this).inflate(R.layout.main_menu_layout, container, false);
                ImageView icon = (ImageView) view.findViewById(R.id.icon);
                TextView name = (TextView) view.findViewById(R.id.name);
                name.setText(adapter.getPageTitle(position));
                switch (position) {
                    case 0:
                        icon.setImageDrawable(getResources().getDrawable(R.drawable.nearby_home_menu_selector));
                        break;
                    case 1:
                        icon.setImageDrawable(getResources().getDrawable(R.drawable.nearby_message_menu_selector));
                        break;
                    case 2:
                        icon.setImageDrawable(getResources().getDrawable(R.drawable.nearby_me_menu_selector));
                        break;
                    default:
                        throw new IllegalStateException("Invalid position: " + position);
                }
                return view;
            }
        });

    }


}
